using System;
using System.Xml.Linq;
using IDeal.Models;
using IDeal.Services;

namespace IDeal.Serialization
{
    internal abstract class XmlMessageReader<T> : IXmlMessageReader<T> where T : XmlResponse
    {
        private readonly IIDealServices _iDealServices;
        protected readonly XNamespace Ns = XNamespace.Get("http://www.idealdesk.com/Message");

        protected XmlMessageReader(IIDealServices iDealServices)
        {
            _iDealServices = iDealServices;
        }

        public T FromXml(string xml)
        {
            var instance = _iDealServices.Activator.CreateInstance<T>();
            var document = XDocument.Parse(xml);
            var rootElement = document.Root;
            var createDateTimeStampElement = rootElement.Element(Ns + "createDateTimeStamp");

            instance.CreateDateTimeStamp = DateTime.Parse(createDateTimeStampElement.Value);
            ParseRootElement(instance, rootElement);

            return instance;
        }

        protected abstract void ParseRootElement(T instance, XElement rootElement);
    }
}